package com.zx.mes.hyl.upms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.mes.controller.BaseController;
import com.zx.mes.hyl.upms.entity.SysMenu;
import com.zx.mes.hyl.upms.entity.SysRole;
import com.zx.mes.hyl.upms.entity.SysRoleMenu;
import com.zx.mes.hyl.upms.entity.SysUserRole;
import com.zx.mes.hyl.upms.pagemodel.TreeNode;
import com.zx.mes.hyl.upms.service.SysMenuService;
import com.zx.mes.hyl.upms.service.SysRoleMenuService;
import com.zx.mes.hyl.upms.service.SysRoleService;
import com.zx.mes.hyl.upms.service.SysUserRoleService;
import com.zx.mes.response.ObjectRestResponse;
import com.zx.mes.response.TableResultResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2018-07-09
 */
@CrossOrigin
@RestController
@RequestMapping("/sysRole")
public class SysRoleController extends BaseController<SysRoleService, SysRole> {

    private final SysUserRoleService sysUserRoleService;

    private final SysRoleMenuService sysRoleMenuService;

    private final SysMenuService sysMenuService;

    @Autowired
    public SysRoleController(SysUserRoleService sysUserRoleService, SysRoleMenuService sysRoleMenuService,SysMenuService sysMenuService) {
        this.sysUserRoleService = sysUserRoleService;
        this.sysRoleMenuService = sysRoleMenuService;
        this.sysMenuService = sysMenuService;
    }

    @Override
    public ObjectRestResponse<SysRole> add(@RequestBody SysRole sysRole) {
        sysRole.setId(UUID.randomUUID().toString());
        return super.add(sysRole);
    }

    @Override
    public ObjectRestResponse<SysRole> update(@RequestBody SysRole sysRole) {
        if (StringUtils.isBlank(sysRole.getPid())) {
            sysRole.setPid(null);
        }
        return super.update(sysRole);
    }

    @Override
    public TableResultResponse<SysRole> list(@RequestParam Map<String, Object> params, SysRole sysRole) {
        int page = Integer.valueOf(params.get("page").toString());
        int limit = Integer.valueOf(params.get("limit").toString());

        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if (sysRole != null && StringUtils.isNotBlank(sysRole.getName())) {
            wrapper.like("name", sysRole.getName());
        }

        List<SysRole> list = this.biz.page(new Page(page, limit), wrapper).getRecords();
        TableResultResponse<SysRole> response;
        if (list == null) {
            response = new TableResultResponse.Builder<SysRole>()
                    .message("无数数据")
                    .page(page)
                    .total(0L)
                    .rows(null)
                    .build();
        } else {
            response = new TableResultResponse.Builder<SysRole>()
                    .message("分页查询结果")
                    .status(200)
                    .rows(list)
                    .page(page)
                    .total(biz.count(wrapper))
                    .build();
        }

        return response;

    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/grantMenu")
    public ObjectRestResponse grantMenu(@RequestBody SysRole sysRole) {
        ObjectRestResponse response = new ObjectRestResponse();
        /// 1.获取所有的menu id
        String[] ids = sysRole.getMenuIds().split(",");
        List<SysRoleMenu> list = new ArrayList<>();
        /// 3.拼接SysRoleMenu
        for (String id : ids) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(UUID.randomUUID().toString());
            sysRoleMenu.setRoleId(sysRole.getId());
            sysRoleMenu.setMenuId(id);
            list.add(sysRoleMenu);
        }
        /// 4.授权之前先删除对应权限
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().lambda().eq(SysRoleMenu::getRoleId, sysRole.getId()));
        /// 5.对已存在的角色进行授权，只需要对中间表进行操作
        try {
            sysRoleMenuService.saveBatch(list, list.size());
            response.setMessage("角色授权成功!");
        } catch (Exception e) {
            response.setStatus(500);
            response.setMessage("角色授权失败:" + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/deleteBatch")
    public ObjectRestResponse<String> deleteBatch(String ids) {
        ObjectRestResponse<String> response = new ObjectRestResponse<>();
        try {
            /// 删除父子之间的关系
            List<SysRole> list = biz.list(new QueryWrapper<SysRole>().lambda().in(SysRole::getPid, ids));
            for (int i = 0; i <list.size() ; i++) {
                SysRole role = list.get(i);
                role.setPid("");
                list.set(i, role);
            }
            if (list.size() > 0) {
                biz.saveOrUpdateBatch(list, list.size());
            }

            /// 删除sysRole表中的数据
            biz.removeByIds(Arrays.asList(ids.split(",")));
            /// 删除sysUserRole表中对应的数据
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>()
                    .in("role_id", ids));
            /// 删除sysRoleMenu表中对应的数据
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>()
                    .in("role_id", ids));
        } catch (Exception e) {
            response.setMessage(e.getMessage());
            response.setStatus(500);
            e.printStackTrace();
        }
        response.setMessage("批量删除成功!");
        return response;
    }

    @GetMapping("/getRoleAndMenuTreeNode")
    public ObjectRestResponse<SysRole> getRoleAndMenuTreeNode(String id){
        /// 1.判断角色id,不能为空，不能为"" ," "
        if (StringUtils.isNotBlank(id)) {
            /// 2.角色菜单中间表查找 角色与权限对应的关系
            List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().lambda().eq(SysRoleMenu::getRoleId, id));
            List<String> menuIds = new ArrayList<>();
            /// 3.如果有对应关系数据,则遍历,===>获取菜单id集合
            if (roleMenuList.size() > 0) {
                for (SysRoleMenu roleMenu : roleMenuList) {
                    menuIds.add(roleMenu.getMenuId());
                }
                /// 4.查询所有的菜单
                Collection<SysMenu> sysMenus = sysMenuService.listByIds(menuIds);

                return new ObjectRestResponse.Builder<SysRole>().data(new SysRole().setMenuList((List<SysMenu>) sysMenus)).message("角色菜单树获取成功!").build();
            }else{
                /// 3.如果无对应关系数据,则返回空的menuList,让返回接口统一
                return new ObjectRestResponse.Builder<SysRole>().data(new SysRole().setMenuList(null)).message("所传角色id值不能为空或空字符串!").build();
            }

        }else{
            return new ObjectRestResponse.Builder<SysRole>().data(null).message("所传角色id值不能为空或空字符串!").build();
        }

    }

    /**
     * 角色 树结构获取
     *
     * @return TableResultResponse
     */
    @GetMapping("/treeNodesRole")
    public TableResultResponse<TreeNode> treeNodesRole() {
        /// 获取所有的角色
        List<SysRole> roleList = biz.list(new QueryWrapper<>());
        List<TreeNode> list = new ArrayList<>();
        List<TreeNode> nodeList = new ArrayList<>();
        /// 将集合类型进行转换 SysRole --> TreeNode
        for (SysRole sysRole : roleList) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(sysRole.getId());
            treeNode.setKey(sysRole.getId());
            treeNode.setTitle(sysRole.getName());
            treeNode.setLabel(sysRole.getName());
            treeNode.setValue(sysRole.getId());
            treeNode.setPid(sysRole.getPid());
            nodeList.add(treeNode);
        }
        /// 做递归操作
        for (int i = 0; i < nodeList.size(); i++) {
            TreeNode node = nodeList.get(i);
            if (!StringUtils.isNotBlank(node.getPid())) {
                list.add(getChildNodes(nodeList, node));
            }
        }

        return new TableResultResponse.Builder<TreeNode>()
                    .total(list.size())
                    .page(0)
                    .rows(list)
                    .build();
    }

    /**
     * 递归的具体操作
     *
     * @param nodeList nodeList
     * @param treeNode treeNode
     * @return TreeNode
     */
    private TreeNode getChildNodes(List<TreeNode> nodeList, TreeNode treeNode) {
        for (int i = 0; i < nodeList.size(); i++) {
            TreeNode node = nodeList.get(i);
            if (StringUtils.isNotBlank(node.getPid()) && node.getPid().equals(treeNode.getId())) {
                treeNode.getChildren().add(node);
                getChildNodes(nodeList, node);
            }
        }
        return treeNode;
    }
}

